package engine.input;

import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;

public class KeyInput {

    KeyUnit[] units;

    public Key isKey;

    public KeyInput() {
        isKey=Key.nul;
        units = new KeyUnit[Key.values().length];
        for (int i = 0; i < units.length; i++) {
            units[i] = new KeyUnit();
        }
    }

    //获取按键相关的数据 按下 松开 按住
    public boolean isPressed(Key key) {
        isKey=key;
        return key != null && units[key.ordinal()].pressed;
    }

    public boolean isReleased(Key key) {
        return key != null && units[key.ordinal()].released;
    }

    public boolean isHeld(Key key) {
        isKey=key;
        return key != null && units[key.ordinal()].held;
    }

    //按键的敲击次数
    public int getTypeCount(Key key) {
        return key != null ? units[key.ordinal()].typeCount : 0;
    }

    //判断是否敲击了
    public boolean isType(Key key) {
        return getTypeCount(key) > 0;
    }

    //操作按键的方法 按下一个按键
    public void press(Key key) {
        if (key != null) {
            units[key.ordinal()].press();
        }
    }

    //松开一个按键
    public void release(Key key) {
        if (key != null) {
            units[key.ordinal()].release();
        }
    }

    //输入单元的刷新方法
    public void refresh() {
        for (KeyUnit unit : units) {
            unit.refresh();
        }
    }

    //输入单元的重置方法
    public void reset() {
        for (KeyUnit unit : units) {
            unit.reset();
        }
    }

    //安装键盘事件监听器
    public void install(Stage stage) {
        stage.addEventHandler(KeyEvent.KEY_PRESSED, this::handleKeyPressed);
        stage.addEventHandler(KeyEvent.KEY_RELEASED, this::handleKeyReleased);
        reset();
    }

    //卸载键盘事件监听器
    public void uninstall(Stage stage) {
        stage.removeEventHandler(KeyEvent.KEY_PRESSED, this::handleKeyPressed);
        stage.removeEventHandler(KeyEvent.KEY_RELEASED, this::handleKeyReleased);
        reset();
    }

    private void handleKeyPressed(KeyEvent event) {
        press(Key.find(event.getCode()));
        //press(Key.find(event.getText()));
    }

    private void handleKeyReleased(KeyEvent event) {
        release(Key.find(event.getCode()));
        //release(Key.find(event.getText()));
    }
}
